﻿using AutoMapper;
using Ducu.BLL.Entity;
using Ducu.SRV.Query;
using Ducu.SRV.ServiceInteface;
using Ducu.SRV.ViewModel.User;
using NHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Ducu.SRV.ProdService
{
    public class UserService : BaseService, IUserService
    {
        public ProfileModel Get(int id)
        {
            User user = repoFactory.Load<User>(id);

            return new ProfileModel
            {
                UserName = user.Profile.DisplayName,
            };
        }

        public _CreditModel GetCredit(int userId)
        {
            _CreditModel model = new _CreditModel();

            User executor = repoFactory.Load<User>(userId);
            var onExecutor = repoFactory.Query<HistoryItem>().Get(executor);
            model.All = onExecutor.Count();
            if (model.All > 0)
            {
                DateTime lastest =
                    onExecutor.OrderByDescending(h => h.CreateTime).First().CreateTime;
                model.LatestGainDaysBefore = (DateTime.Now.Date - lastest.Date).Days;
                model.LatestGainNumber = repoFactory.Query<HistoryItem>()
                    .Get(executor, lastest).Count();
            }

            return model;
        }

        public string GetDisplayName(int userId)
        {
            return repoFactory.Load<User>(userId).Profile.DisplayName;
        }

        public CreditsModel GetCreditsList(int userId, GLB.Global.Pager pager)
        {
            CreditsModel model = new CreditsModel();

            User user = repoFactory.Load<User>(userId);
            var currentPage = repoFactory.Query<HistoryItem>().Get(user)
                .OrderByDescending(h=>h.CreateTime)
                .Page(pager);

            model.Items = Mapper.Map<IList<CreditItemModel>>(currentPage.ToList());

            return model;

        }

        public int GetCreditsCount(int userId)
        {
            User user = repoFactory.Load<User>(userId);
            return repoFactory.Query<HistoryItem>().Get(user).Count();
        }
    }
}
